<?php
/**
 *      [cdvphp!] (C)2012 - 2099 www.cdvphp.com
 *
 *      $Id: error.php 2013-10-16 10:10:10 fanjiapeng $
 */

if(!defined('IN_CORE')) {
	exit('Access Denied');
}

class class_error
{
	static function system_error($message = '', $show = TRUE, $save = TRUE, $halt = TRUE) {

		$message = lang('error', empty($message) ? 'error_unknow': $message);

		list($showtrace, $logtrace) = class_error::debug_backtrace();

		if($save) {
			$messagesave = "<b>{$message}</b><br><b>PHP:</b>{$logtrace}";
			self::write_error_log($messagesave);
		}

		if($show) {
			self::show_error('system', "<li>{$message}</li>", $showtrace);
		}

		if($halt) {
			exit();
		} else {
			return $message;
		}
	}

	static function template_error($message, $tplname) {
		$message = lang('error', $message);
		$tplname = str_replace(array(FRAMEWORK_PATH, ROOT_PATH), '', $tplname);
		$message = $message.': '.$tplname;
		
		self::write_error_log($message);
		list($showtrace, $logtrace) = class_error::debug_backtrace();
		self::show_error('template', "<li>$message</li>", $showtrace, 1);
	}

	static function debug_backtrace() {

		$skipfunc[] = 'class_error->debug_backtrace';
		$skipfunc[] = 'class_error->db_error';
		$skipfunc[] = 'class_error->template_error';
		$skipfunc[] = 'class_error->system_error';
		$skipfunc[] = 'db_mysql->halt';
		$skipfunc[] = 'db_mysql->query';
		$skipfunc[] = 'db::_execute';

		$show = $log = '';
		$debug_backtrace = debug_backtrace();
		
		krsort($debug_backtrace);
		foreach ($debug_backtrace as $k => $error) {
			$file = str_replace(array(FRAMEWORK_PATH, ROOT_PATH), '', $error['file']);
			$func = isset($error['class']) ? $error['class'] : '';
			$func .= isset($error['type']) ? $error['type'] : '';
			$func .= isset($error['function']) ? $error['function'] : '';
			
			if($func == 'class_core::instance') continue;
			if(in_array($func, $skipfunc)) break;
			
			$error['line'] = sprintf('%04d', $error['line']);

			$show .= "<li>[Line: {$error['line']}]".$file."($func)</li>";
			$log .= !empty($log) ? ' -> ' : '';$file.':'.$error['line'];
			$log .= $file.':'.$error['line'];
		}

		return array($show, $log);
	}

	static function db_error($message, $sql) {
		global $_G;

		list($showtrace, $logtrace) = class_error::debug_backtrace();

		$title = lang('error', 'db_'.$message);
		$title_msg = lang('error', 'db_error_message');
		$title_sql = lang('error', 'db_query_sql');
		$title_backtrace = lang('error', 'backtrace');
		$title_help = lang('error', 'db_help_link');

		$db = db::getdb();

		$dberrno = $db->errno();
		$dberror = str_replace($db->tablepre,  '', $db->error());
		$sql = htmlspecialchars(str_replace($db->tablepre,  '', $sql));

		$msg = '<li>[Type] '.$title.'</li>';
		$msg .= $dberrno ? '<li>['.$dberrno.'] '.$dberror.'</li>' : '';
		$msg .= $sql ? '<li>[Query] '.$sql.'</li>' : '';

		class_error::show_error('db', $msg, $showtrace);

		$errormsg = '<b>'.$title.'</b>';
		$errormsg .= "[$dberrno]<br /><b>ERR:</b> $dberror<br />";
		if($sql) {
			$errormsg .= '<b>SQL:</b> '.$sql;
		}
		$errormsg .= "<br />";
		$errormsg .= '<b>PHP:</b> '.$logtrace;

		class_error::write_error_log($errormsg);
		
		unset($showtrace, $logtrace, $msg, $db, $errormsg);
		exit();
	}

	static function show_error($type, $errormsg, $phpmsg = '', $exit = false) {
		global $_G;

		ob_end_clean();
		ob_start($_G['config']['output']['gzip'] ? 'ob_gzhandler' : null);

		$host   = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '127.0.0.1';
		$phpmsg = trim($phpmsg);
		$title  = ucfirst($type);

		if($_G['config']['system']['debug'] < 1) {
			$errormsg = lang('error', 'system_debug');
			$title = $type = $phpmsg = '';
		}
		echo <<<EOT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
	<title>$host - $title Error</title>
	<meta http-equiv="Content-Type" content="text/html; charset={$_G['config']['output']['charset']}" />
	<meta name="ROBOTS" content="NOINDEX,NOFOLLOW,NOARCHIVE" />
	<style type="text/css">
	<!--
	body { background-color: white; color: black; }
	#container { width: 650px; }
	#message   { width: 650px; color: black; background-color: #FFFFCC; }
	#bodytitle { font: 13pt/15pt verdana, arial, sans-serif; height: 35px; vertical-align: top; }
	.bodytext  { font: 10pt/13pt verdana, arial, sans-serif; line-height:18px; }
	.help  { font: 10px verdana, arial, sans-serif;}
	.red  {color: red;}
	a:link     { font: 10pt/13pt verdana, arial, sans-serif; color: #900; }
	a:visited  { font: 10pt/13pt verdana, arial, sans-serif; color: #4e4e4e; }
	-->
	</style>
</head>
<body>
<table cellpadding="1" cellspacing="5" id="container">
<tr>
	<td id="bodytitle" width="100%">CdvPHP Framework $title Error </td>
</tr>
EOT;

		echo <<<EOT
<tr><td><hr size="1"/></td></tr>
<tr><td class="bodytext">Error messages: </td></tr>
<tr>
	<td class="bodytext" id="message">
		<ul> $errormsg</ul>
	</td>
</tr>
EOT;

		if(!empty($phpmsg)) {
			echo <<<EOT
<tr><td class="bodytext">&nbsp;</td></tr>
<tr><td class="bodytext">Program messages: </td></tr>
<tr>
	<td class="bodytext">
		<ul> $phpmsg </ul>
	</td>
</tr>
EOT;
		}
		echo <<<EOT
</table>
</body>
</html>
EOT;
		$exit && exit();
	}

	static function clear($message) {
		return str_replace(array("\t", "\r", "\n"), ' ', $message);
	}

	static function write_error_log($message) {
		global $_G;

		$message = self::clear($message);
		$file =  ROOT_PATH.'./data/logs/'.date('Ym').'_errorlog.php';
		$hash = md5($message);

		$ip = $_G['clientip'];
		$time = $_G['timestamp'];

		$user = '<b>IP:</b> IP='.$ip.'; RIP:'.$_SERVER['REMOTE_ADDR'];
		$uri = 'Request: '.htmlspecialchars(self::clear($_SERVER['REQUEST_URI']));
		$message = "<?PHP exit;?>\t{$time}\t$message\t$hash\t$user $uri\n";

		if($fp = @fopen($file, 'rb')) {
			$lastlen = 10000;
			$maxtime = 60 * 10;
			$offset = filesize($file) - $lastlen;
			flock($fp, LOCK_SH + LOCK_NB);
			if($offset > 0) {
				fseek($fp, $offset);
			}

			if($data = fread($fp, $lastlen)) {
				flock($fp, LOCK_UN + LOCK_NB);
				fclose($fp);
				$array = explode("\n", $data);
				if(is_array($array)) foreach($array as $key => $val) {
					$row = explode("\t", $val);
					if($row[0] != '<?PHP exit;?>') continue;
					if($row[3] == $hash && ($row[1] > $time - $maxtime)) {
						return;
					}
				}
			}
		}

		error_log($message, 3, $file);
	}
}
?>
